package com.newopenlab.hmc.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.newopenlab.hmc.biz.Action;
import com.newopenlab.hmc.biz.Player;

public class SummaryParser {
	public static String SUMMARY_COLLECTED_PRE="collected ";
	public static String SUMMARY_WON_PRE="and won ";
	public BaseHand bh=null;
	public BasicParser basicParser=null;
	public SummaryParser(){
		
	}
	public void parse(String aux) {
		boolean flag=false;
		Player p=null;
		List<Player> players=new ArrayList<Player>(this.bh.seats.values());
		for(int i=0;i<players.size()&&!flag;i++){
			p=players.get(i);
			if(aux.contains(p.name)){
				flag=true;
				parseResult(p,aux);
			}
		}
		
	}
	protected void parseResult(Player p, String aux) {
		String won=null;
		String collected=null;
		won=this.basicParser.getStringAfter(aux, SUMMARY_WON_PRE);
		if(won!=null){
			won=this.basicParser.getStringIn(won, "(", ")",1);
		}
		collected=this.basicParser.getStringAfter(aux, SUMMARY_COLLECTED_PRE);
		if(collected!=null){
			collected=this.basicParser.getStringIn(collected, "(", ")",1);
		}
		Double diff=0D;
		try{
			if(won!=null){
				diff=this.basicParser.nf.parse(won).doubleValue()-this.calculateBets(p);
			}else if(collected!=null){
				diff=this.basicParser.nf.parse(collected).doubleValue()-this.calculateBets(p);;
			}else{
				diff=this.calculateBets(p)*(-1d);
			}
			BigDecimal bd = new BigDecimal(Double.toString(diff));
			bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
			diff=bd.doubleValue();
			
			this.bh.results.get(p.name).result=diff;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
		
		
	}
	private Double calculateBets(Player p) {
		Double d=0d;
		Map<String,Double> bets=new HashMap<String,Double>();
		WayAction ac=null;
		for(int i=0;i<this.bh.actions.size();i++){
			ac=this.bh.actions.get(i);
			try {
				if(//ac.chips>0d && 
						ac.player.name.equals(p.name)){
					Double x=bets.get(ac.way)!=null?bets.get(ac.way):0d;
					if(ac.action.equals(Action.RAISE.getName())){
						x=0d;
					}
					
					bets.put(ac.way, ac.chips+x);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		for(Double dd:bets.values()){
			d=d+dd;
		}
		return d;
	}
}
